package com.algorithm.lesson_04;

import java.util.Stack;

/**
 * 用栈结构实现队列
 * 
 * @author Administrator
 *
 */
public class TwoStacksImplQueue {
	private Stack<Integer> pushStack; // 输入栈
	private Stack<Integer> popStack; // 输出栈

	public TwoStacksImplQueue() {
		pushStack = new Stack<>();
		popStack = new Stack<>();
	}

	/**
	 * 进队
	 * 
	 * @param newNum
	 */
	public void add(Integer newNum) {
		pushStack.push(newNum);
	}

	/**
	 * 出队
	 * 
	 * @return
	 */
	public Integer poll() {

		if (pushStack.isEmpty() && popStack.isEmpty()) {
			// 输入栈和输出栈都为空
			throw new RuntimeException("Your Queue is Empty!");
		} else {
			if (popStack.isEmpty()) {
				// 输出栈为空，将输入栈倒入输出栈
				while (!pushStack.isEmpty()) {
					Integer popInt = pushStack.pop();
					popStack.push(popInt);
				}
			}
		}

		return popStack.pop();
	}

	/**
	 * 查看队头
	 * 
	 * @return
	 */
	public Integer peek() {
		if (pushStack.isEmpty() && popStack.isEmpty()) {
			// 输入栈和输出栈都为空
			throw new RuntimeException("Your Queue is Empty!");
		} else {
			if (popStack.isEmpty()) {
				// 输出栈为空，将输入栈倒入输出栈
				while (!pushStack.isEmpty()) {
					Integer popInt = pushStack.pop();
					popStack.push(popInt);
				}
			}
		}

		return popStack.peek();
	}
}
